package com.android.dblocation

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import com.alibaba.android.arouter.facade.annotation.Route
import com.camera.routemodule.RouterPath
import com.camera.routemodule.routeinterface.BDLocationInterface
import com.camera.routemodule.routeinterface.BDLocationListener

@Route(path = RouterPath.path.baidu_location)
class BDLocationImpl : BDLocationInterface {
    var context:Context? = null
    var mDBLocationBinder: DBLocationBinder? = null
    private val binderEventListeners: MutableSet<BDLocationListener> = mutableSetOf()
    override fun startLocation() {
        if (mDBLocationBinder == null){
            context?.bindService(Intent(context, DBLocationService::class.java),mServiceConnection,Context.BIND_AUTO_CREATE)
        }
    }
    private val mServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            mDBLocationBinder = service as DBLocationBinder
            mDBLocationBinder?.init(context)
            if (binderEventListeners.size > 0){
                binderEventListeners.forEach {
                    mDBLocationBinder?.addLocationListener(it)
                }
            }
            mDBLocationBinder?.startLocation()
        }

        override fun onServiceDisconnected(name: ComponentName) {
//            mCameraBinder.disConnect(CameraApp.getApplication());
            mDBLocationBinder?.stopLocation()
            mDBLocationBinder = null
        }
    }
    override fun stopLocation() {
        if (mDBLocationBinder != null){
            if(mDBLocationBinder!!.getBDLocationListenerSize() <= 0){
                context?.unbindService(mServiceConnection)
                mDBLocationBinder = null
            }
        }

    }

    override fun addLocationListener(listener: BDLocationListener) {
        if (mDBLocationBinder != null) {
            mDBLocationBinder!!.addLocationListener(listener)
        } else {
            binderEventListeners.add(listener)
        }
    }

    override fun removeLocationListener(listener: BDLocationListener) {
        mDBLocationBinder?.removeLocationListener(listener)
    }


    override fun init(context: Context?) {
        this.context = context
    }
}